﻿(function () {
    var _currentCartList = [];
    var sendData = [];
    var _isSaveError = false;
    var _shopName = $(".weui-content").attr("ShopName");
    var said = ToolManager.Common.UrlParms("said");
    var spid = ToolManager.Common.UrlParms("spid");
    ShopCartClass = {};
    ShopCartClass.Instance = {
        Init: function () {
            $(function () {
                ShopCartClass.Instance.GetList();

            })
            //监听数量改变事件
            $(document).on('click', '.Decrease', this.NumChange);
            $(document).on('click', '.Increase', this.NumChange);
            $(document).on('click', '.check-w', this.ChoseCheck);
            $(document).on('click', '.allselect', this.ClickAllChose);
            $(document).on('click', '.wy-dele', this.Del);
            $(document).on('click', '#GoOrder', this.GoOrder);
        },
        GoOrder:function(){
            if (_isSaveError) {
                layer.msg("页面出现错误,请返回首页!");
                return false;
            }
            _currentCartList.forEach((value, index) => {
                if (value.State == 1)
                    sendData.push(value);
            })
            if (sendData.length <= 0) {
                layer.msg("请选择商品");
                return false;
            }
            var isHasExpress = false;
            sendData.forEach((value, index) => {
                if (value.SkuDetail.IsDel == 1)
                    isHasExpress = true;
            })
            if (isHasExpress) {
                layer.msg("请不要提交已被删除的商品");
                return false;
            }
            window.location.href = "/Order/SureOrder?goodList=" + JSON.stringify(sendData) + "&spid=" + spid + "&said=" + said + "&addresid=0&iscart=1";
        },
        Del:function(){
            var skuid = $(this).attr("skuid");
            layer.confirm('确定要删除么？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
               
                _currentCartList =  ShopCartManagerClass.Instance.DeleteSkuBySkuId(_currentCartList, skuid);
                ShopCartClass.Instance.Save();
                window.location.reload();
                //ShopCartClass.Instance.BindData();
                ////ShopCartClass.Instance.UpdateAmountInfo();
                //ShopCartClass.Instance.BindCheck();
                //ShopCartClass.Instance.CheckAllSelectStatus();
                layer.closeAll();
            }, function () {
               
            });
        },
        //全选事件
        ClickAllChose: function () {
            var isAllCheck = true;
            if ($(this).find("input[name=all-sec]").prop("checked")) {
                $("input[name=cartpro]").each(function () {
                    $(this).prop("checked", true);
                });
            }
            else {
                $("input[name=cartpro]").each(function () {
                    $(this).prop("checked", false);
                });
                isAllCheck = false;
            }
            _currentCartList.forEach((value, index) => {
                value.State = isAllCheck ? 1 : 0;
            })
            ShopCartClass.Instance.Save();
        },
        //单个选择框事件
        ChoseCheck: function () {
            var checkDom = $(this).find("input[type='checkbox']");
            var _state = 0;
            if (checkDom.prop("checked")) {
                checkDom.prop("checked", false);
            } else {
                checkDom.prop("checked", true);
                _state = 1;
            }
            var skuid = checkDom.attr("skuid");
            var skumodel = ShopCartManagerClass.Instance.GetModelBySkuId(_currentCartList, skuid);
            skumodel.State = _state;
            ShopCartManagerClass.Instance.UpdateSkuModel(_currentCartList, skumodel);
            ShopCartClass.Instance.CheckAllSelectStatus();
            ShopCartClass.Instance.Save();
        },
        //检测是否全选
        CheckAllSelectStatus: function () {
            var isAll = true;
            _currentCartList.forEach((value, index) => {
                if (value.State == 0)
                    isAll = false;
            })
            if (isAll)
                $(".allselect").find("input[name=all-sec]").prop("checked", true);
            else
                $(".allselect").find("input[name=all-sec]").prop("checked", false);
        },
        //绑定选择框
        BindCheck: function () {
            _currentCartList.forEach((value, index) => {
                if (value.State == 1)
                    $("#check_" + value.Product_SkuId).prop("checked", true);
                else
                    $("#check_" + value.Product_SkuId).prop("checked", false);
            })
        },
        //更新总金额
        UpdateAmountInfo: function () {

            var totalAmount = 0.0;
            _currentCartList.forEach((value, index) => {
                if (value.State != 0) {
                    totalAmount += parseFloat(value.SkuDetail.SallPrice) * value.SaleNum;
                }
            })
            $("#totalAmount").html(totalAmount.toFixed(2));
        },
        //数量事件
        NumChange: function () {
            var skuid = $(this).parent().attr("skuid");
            var num = $(this).parent().find("input[class='Amount']").val();
            var skumodel = ShopCartManagerClass.Instance.GetModelBySkuId(_currentCartList, skuid);
         
            if (parseInt(num) > skumodel.SkuDetail.StockNum) {
                layer.msg("不能超过该规格商品库存");
                return false;
            }
            skumodel.SaleNum = parseInt(num);
            ShopCartManagerClass.Instance.UpdateSkuModel(_currentCartList, skumodel);

            ShopCartClass.Instance.Save();
        },
        //保存当前购物车列表模型
        Save: function () {
            var index = layer.load(1);

            //var list = ShopCartManagerClass.Instance.GetEasySkuModelList(_currentCartList);
            RequestManager.Ajax.Post("/Cart/Set?spid=" + spid + "&said=" + said, _currentCartList, true, function (data) {
                layer.close(index);

                if (data.IsSuccess) {
                    ShopCartClass.Instance.UpdateAmountInfo();
                } else {
                    _isSaveError = true;
                    layer.msg(data.Message);
                }
            })
        },
        //读取购物车模型
        GetList: function () {
            var index = layer.load(1);
            $.get("/Cart/GetList?said=" + said + "&spid=" + spid + "&r=" + new Date().getTime(), function (data) {
                layer.close(index);

                if (data.IsSuccess) {

                    if (data.Data.length > 0) {
                        _currentCartList = data.Data;
                        var _skuids = ShopCartManagerClass.Instance.ConvertToSkuids(data.Data);
                        ShopCartClass.Instance.SetFullList(_skuids);
                    } else {
                        //没数据
                        $("#div_cartNull").show();
                    }

                } else {
                    layer.msg(data.Message);
                }
            })
        },
        //给购物车模型设置详细模型
        SetFullList: function (skuids) {
            var index = layer.load(1);
            $.get("/Cart/GetShopCartModelList?skuids=" + skuids + "&said=" + said + "&spid=" + spid + "&r=" + new Date().getTime(), function (data) {
                layer.close(index);

                if (data.IsSuccess) {
                    //将sku模型赋值
                    _currentCartList = ShopCartManagerClass.Instance.GetFullSkuModel(_currentCartList, data.Data);
                    ShopCartClass.Instance.BindData();
                    ShopCartClass.Instance.UpdateAmountInfo();
                    ShopCartClass.Instance.BindCheck();
                    ShopCartClass.Instance.CheckAllSelectStatus();
                } else {
                    layer.msg(data.Message);
                }
            })
        },
        //绑定购物车模型到页面
        BindData: function () {
            
            if (_currentCartList.length <= 0) {
                $("#div_cartNull").show();
                
            } else {
                $("#div_cartNull").hide();
            }
            var arr = [];
            for (var i = 0; i < _currentCartList.length; i++) {
                arr.push('<div class="weui-panel weui-panel_access">');
                arr.push('<div class="weui-panel__hd"><span>' + _shopName + '</span><a href="javascript:;" class="wy-dele" skuid="' + _currentCartList[i].Product_SkuId + '"></a></div>');
                arr.push('<div class="weui-panel__bd">');
                arr.push(' <div class="weui-media-box_appmsg pd-10">');
                arr.push('<div class="weui-media-box__hd check-w weui-cells_checkbox">');
                arr.push('<label class="weui-check__label" for="cart-pto1">');
                arr.push('<div class="weui-cell__hd cat-check">');
                arr.push(' <input type="checkbox" class="weui-check" id="check_' + _currentCartList[i].Product_SkuId + '" skuid="' + _currentCartList[i].Product_SkuId + '" name="cartpro">');
                arr.push('<i class="weui-icon-checked"></i>');
                arr.push(' </div>');
                arr.push('</label>');
                arr.push('</div>');
                arr.push(' <div class="weui-media-box__hd"><a href="/Product/Detail?spid=' + spid + '&said=' + said + '&id=' + _currentCartList[i].ProductId + '"><img class="weui-media-box__thumb" src="' + _currentCartList[i].SkuDetail.ImgPath + '" alt=""></a></div>');
                arr.push('<div class="weui-media-box__bd">');
                arr.push('<h1 class="weui-media-box__desc"><a href="/Product/Detail?spid=' + spid + '&said=' + said + '&id=' + _currentCartList[i].ProductId + '" class="ord-pro-link">' + _currentCartList[i].SkuDetail.Brand + ' ' + _currentCartList[i].SkuDetail.ProductName + '</a></h1>');
                arr.push(' <p class="weui-media-box__desc">' + _currentCartList[i].SkuDetail.ProppetyCombineName + '</p>');
                arr.push('<div class="clear mg-t-10">');
                arr.push('<div class="wy-pro-pri fl">¥<em class="num font-15">' + _currentCartList[i].SkuDetail.SallPrice + (_currentCartList[i].SkuDetail.IsDel == 0 ? "" : "(该规格已过期,请手动删除)") + '</em></div>');
                arr.push('<div class="pro-amount fr" ><div class="Spinner" id="spinner_' + _currentCartList[i].Product_SkuId + '" SkuId="' + _currentCartList[i].Product_SkuId + '"></div></div>');

                arr.push(' </div>');
                arr.push(' </div>');
                arr.push(' </div>');
                arr.push(' </div>');
                arr.push(' </div>');
            }
            $(".weui-content").html(arr.join(''));
            //绑定spinner键盘
            for (var j = 0; j < _currentCartList.length; j++) {
                $("#spinner_" + _currentCartList[j].Product_SkuId).Spinner({ value: _currentCartList[j].SaleNum, len: 3, max: 999, min: 1 });
            }
            //$(".Spinner").Spinner({ value: 1, len: 3, max: 999 });
        },
    };

})();